package com.ilop.siteraudio.util.okhttp;

import com.parkingwang.okhttp3.LogInterceptor.LogInterceptor;

import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @author skygge
 * @date 2/24/21.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：
 */
public class OkHttpClientUtils {

    private volatile static OkHttpClientUtils instance = null;
    private final OkHttpClient mClient;

    public OkHttpClientUtils() {
        mClient = new OkHttpClient.Builder()
                .addInterceptor(new LogInterceptor())
                .readTimeout(100, TimeUnit.SECONDS)//设置读取超时时间
                .writeTimeout(60, TimeUnit.SECONDS)//设置写的超时时间
                .connectTimeout(60, TimeUnit.SECONDS)//设置连接超时时间
                .build();
    }

    public static OkHttpClientUtils getInstance(){
        if (instance == null){
            synchronized (OkHttpClientUtils.class){
                if (instance == null){
                    instance = new OkHttpClientUtils();
                }
            }
        }
        return instance;
    }

    public void onPostMessage(String url, String json, OnHttpResponseCallBack mCallBack) {
        HashMap<String,String> da = new HashMap<>();
        da.put("Content-Type","application/json; charset=utf-8");
        RequestBody formBody = new FormBody.Builder()
                .add("data", json)
                .build();
        Request request = new Request.Builder().headers(Headers.of(da))
                .url(url)
                .post(formBody)
                .build();
        try {
            Response response = mClient.newCall(request).execute();
            if (response.isSuccessful()) {
                mCallBack.onSuccessful(response);
            }else {
                mCallBack.onFailure();
            }
        }catch (IOException e){
            mCallBack.onFailure();
        }
    }
}